#include "Send.h"
#include "Package.h"
#include <Timer.h>
#include "LED.h"

module SendC{
	provides interface SendControl;
	provides interface SendFunctions;
	uses interface AMSend;
	uses interface Packet;
	uses interface AMPacket;
	uses interface Timer<TMilli> as Timer0;
	uses interface Timer<TMilli> as Timer1;
	uses interface LEDControl;
	uses interface SplitControl as AMControl;
	
	// TEST
	uses interface Data;
	
}
implementation{

	int counter;
	bool busy;
	message_t pkt;
	Package package;
	uint32_t lastTime;
	
	async command void SendControl.start()
	{
		call AMControl.start();
	}
	
	async command void SendControl.stop()
	{
		call AMControl.stop();
	}
	
	async command void SendControl.startTransmitting(){
		char test1[24] = "startTransmitting called";
		call Timer0.startPeriodic(2000);
		//call Data.Test(test1);
			
	}
	
	async command void SendControl.stopTransmitting(){
		char test[23] = "stopTransmitting called";
		call Timer0.stop();
	}

	event void AMControl.startDone(error_t err)
	{
		if(err == SUCCESS )
		{
		}
			else
		{
			call AMControl.start();	
		}
	}
	
	event void AMControl.stopDone(error_t err)
	{
		call Timer0.stop();
	}

	event void AMSend.sendDone(message_t * msg, error_t error) 
	{
		if(&pkt == msg) 
		{
			busy = FALSE;
			call LEDControl.Off(LEDState_ModeSend);		
		}
	}
	
	void SendPackage(Package * packPtr, bool timerOn)
	{
		char test[14] = "Data sendt: ";
		if( ! busy) 
		{	
			int i;
			Package * mmptr;
			pkt.data[128];
			mmptr = (Package * )(call Packet.getPayload(&pkt,TOSH_DATA_LENGTH ));
				mmptr->data[i] = packPtr->data[i];
	
			if(call AMSend.send(AM_BROADCAST_ADDR, &pkt, TOSH_DATA_LENGTH) == SUCCESS) 
			{
				busy = TRUE;
				call LEDControl.On(LEDState_ModeSend);
				if(timerOn == TRUE){
					call Timer1.startOneShot(35);
					lastTime = call Timer1.getNow();
				}
			}
		}
	}
	
	async command void SendFunctions.sendNewPackage(Package* ptr, bool TimerOn)
	{
		SendPackage(ptr, TimerOn);
	}

	async command uint32_t SendFunctions.readAndStopTimer()
	{
		uint32_t now = call Timer1.getNow();
		call Timer1.stop();
		if(lastTime < now)
			return now - lastTime;
		else
			return 65535 - lastTime + now;
	}
	
	event void Timer0.fired() 
	{
		int i;
		Package* ptr = &package;
		char test2[20] = "Timer0.Fired";
		for(i = 0; i < DATA_SIZE; i++)
			ptr->data[i] = 'h';
			
		counter++;
//		ptr->numbers = counter;
//		ptr->packageId = counter;
//		ptr->ack = FALSE;
//		ptr->time_value = 0;
		ptr->id = TOSH_DATA_LENGTH;
		
		call Data.Test("Sender:");
		call Data.Stream(ptr);
		
		SendPackage(ptr, TRUE);
	}

	event void Timer1.fired(){
		/*Package* ptr = &package;
		char test3[20] = "Timer1.Fired";
		ptr->numbers = counter;
		ptr->packageId = counter;
		ptr->ack = FALSE;
		ptr->time_value = 0;
		SendPackage(ptr, TRUE);
		call Timer1.startOneShot(35);
		lastTime = call Timer1.getNow();
		*/
	}
}